package com.example.orderminiappapi.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.example.orderminiappapi.bean.*;
import com.example.orderminiappapi.service.*;
import com.example.orderminiappapi.tool.Createuuid;
import com.example.orderminiappapi.tool.GetTime;
import com.example.orderminiappapi.utils.webSocket.WebSocketServer;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
public class MealController {

    @Autowired
    private MealService mealService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private UserService userService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private CommentAndTagService commentAndTagService;

    /**
     * 获取某个餐厅的菜单
     */
    @ResponseBody
    @RequestMapping(value = "/getShopMeals", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getShopMeals(@RequestBody Shop shop) throws JsonProcessingException {

        List<Meal> meals = mealService.getShopMeals(shop);

        HashMap hs = new HashMap();//创建对象
        hs.put("meals", meals);

        Shop returnShop = shopService.searchShopDetailByShopId(shop);

        hs.put("shop", returnShop);

        hs.put("comments", commentAndTagService.getOneShopComment(shop));
        hs.put("tags", commentAndTagService.getOneShopTag(shop));

        Response response = new Response("10000", "成功", hs);
        return response;
    }


    /**
     * 后台管理相关接口
     */

    /**
     * 获取某个餐厅的菜单
     */
    @ResponseBody
    @RequestMapping(value = "/getShopMealsByToken", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getShopMealsByToken(HttpServletRequest request) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        Shop shop = new Shop();
        shop.setShopId(shopId);

        List<Meal> meals = mealService.getShopMeals(shop);

        Response response = new Response("10000", "成功", meals);
        return response;
    }

    /**
     * 商家添加mealItem
     */
    @ResponseBody
    @RequestMapping(value = "/doAddMeal", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doAddMeal(HttpServletRequest request, @RequestBody Meal meal) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        Createuuid createuuid = new Createuuid();
        String uuid = createuuid.getOrderIdByUUId();

        meal.setShopId(shopId);
        meal.setMealId(uuid);

        mealService.doAddMeal(meal);

        Response response = new Response("10000", "成功", "成功");
        return response;
    }

    /**
     * 商家或管理员修改mealItem
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdateMeal", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doUpdateMeal(HttpServletRequest request, @RequestBody Meal meal) throws IOException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("userId").asString();

        User user = new User();
        user.setUserId(userId);
        User performer = userService.findShopOwner(user);

        Meal meal1 = mealService.selectOneMeal(meal);

        if(!Objects.equals(meal1.getMealName(), meal.getMealName()) || !Objects.equals(meal1.getMealLogo(), meal.getMealLogo()) || meal1.getMonthlySales() != meal.getMonthlySales()) {
            mealService.doUpdateMeal(meal);
            if(performer.getUserRole() == 3) {
                Notice notice = new Notice();

                Createuuid createuuid = new Createuuid();
                String uuid = createuuid.getOrderIdByUUId();
                notice.setNoticeId(uuid);

                GetTime getTime = new GetTime();
                String createTime = getTime.getNowTime();
                notice.setCreateTime(createTime);

                notice.setPerformerId(userId);
                notice.setPerformerName(performer.getUserName());

                notice.setPassiveId(meal1.getMealId());
                notice.setPassiveName(meal1.getMealName());
                notice.setShopId(meal1.getShopId());
                notice.setType(4);

                noticeService.addNotice(notice);
                WebSocketServer.sendInfo("有新通知,请查看", meal1.getShopId());

                Response response = new Response("10000", "成功", "修改成功");
                return response;
            }
        }

        Response response = new Response("10000", "成功", "成功");
        return response;
    }

    /**
     * 菜品的上架下架
     */
    @ResponseBody
    @RequestMapping(value = "/updateGround", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response updateGround(@RequestBody Meal meal) {

        mealService.updateGround(meal);

        Response response = new Response("10000", "成功", "成功");
        return response;
    }


    /**
     * 删除mealItem
     */
    @ResponseBody
    @RequestMapping(value = "/deleteMealItem", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response deleteMealItem(HttpServletRequest request, @RequestBody Meal meal) throws IOException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("userId").asString();

        User user = new User();
        user.setUserId(userId);
        User performer = userService.findShopOwner(user);

        if(performer.getUserRole() == 3) {
            Notice notice = new Notice();

            Createuuid createuuid = new Createuuid();
            String uuid = createuuid.getOrderIdByUUId();
            notice.setNoticeId(uuid);

            GetTime getTime = new GetTime();
            String createTime = getTime.getNowTime();
            notice.setCreateTime(createTime);

            notice.setPerformerId(userId);
            notice.setPerformerName(performer.getUserName());

            Meal meal1 = mealService.selectOneMeal(meal);
            notice.setPassiveId(meal1.getMealId());
            notice.setPassiveName(meal1.getMealName());
            notice.setShopId(meal1.getShopId());
            notice.setType(5);

            noticeService.addNotice(notice);
            WebSocketServer.sendInfo("有新通知,请查看", meal1.getShopId());
        }

        mealService.deleteMealItem(meal);

        Response response = new Response("10000", "成功", "成功");
        return response;
    }

}
